<template>
  <q-form @submit="submit" ref="myForm" class="q-gutter-md dialog-content" style="height: 567px">
    <div style="height: 515px">
      <GatewayDetail v-bind="$attrs"/>
      <div class="full-width flex items-center justify-center" style="height: 340px" v-if="!tagTab.length">
        <AddIcon title="添加设备" @click="addTab" />
      </div>
      <div v-else>
        <div class="flex justify-between items-center" style="margin: 20px">
          <div>关联设备信息</div>
          <q-icon class="iconfont icontubiao-67" style="cursor: pointer;font-size: 12px" @click="closeBind"></q-icon>
        </div>
        <div v-for="item in tagTab" :key="item.name" :name="item.name">
          <div class="content-container">
            <div class="flex">
              <q-select v-model="item.form.assetNumber"
                        :options="item.numOption"
                        dense
                        options-dense
                        emit-value
                        map-options
                        outlined
                        :disable="!item.numOption || item.numOption.length === 1 && item.ispreStep"
                        class="select-width margin-r-20"
                        :rules="[ val => val !== '' || ' 请选择设备编号']">
                <template v-slot:option="scope">
                  <q-item
                    v-bind="scope.itemProps"
                    v-on="scope.itemEvents"
                  >
                    <q-item-section>
                      <q-item-label v-html="scope.opt.value" ></q-item-label>
                    </q-item-section>
                    <q-item-section side>
                      <q-item-label v-html="scope.opt.name" />
                    </q-item-section>
                  </q-item>
                </template>
                <template v-slot:no-option>
                  <div class="no-option" />
                </template>
                <template v-slot:before>
                  <label class="text-right name label-width">
                    <span class="text-red">*</span><span>设备编号:</span>
                  </label>
                </template>
              </q-select>
              <label class="text-right name label-width">
                <span class="text-red">*</span><span>设备类型:</span>
              </label>
              <label class="name label-width margin-l-10" style="width: 178px;">{{ item.form.deviceTypeIot }}</label>
            </div>
            <div class="flex">
              <q-select v-model="item.form.deviceFactoryIot"
                        :options="item.factoryOption"
                        dense
                        options-dense
                        emit-value
                        map-options
                        outlined
                        class="select-width margin-r-20"
                        :rules="[ val => val !== '' || ' 请选择设备厂家']">
                <template v-slot:no-option>
                  <div class="no-option" />
                </template>
                <template v-slot:before>
                  <label class="text-right name label-width">
                    <span class="text-red">*</span><span>设备厂家:</span>
                  </label>
                </template>
              </q-select>
              <q-select v-model="item.form.deviceSerialIot"
                        :options="item.modelOption"
                        dense
                        options-dense
                        emit-value
                        map-options
                        outlined
                        class="select-width"
                        :rules="[ val => val !== '' || ' 请选择设备型号']">
                <template v-slot:no-option>
                  <div class="no-option" />
                </template>
                <template v-slot:before>
                  <label class="text-right name label-width">
                    <span class="text-red">*</span><span>设备型号:</span>
                  </label>
                </template>
              </q-select>
            </div>
            <div class="flex">
              <q-select v-model="item.form.deviceProtocolIot"
                        :options="item.protocolOption"
                        dense
                        options-dense
                        emit-value
                        map-options
                        outlined
                        class="select-width margin-r-20"
                        :rules="[ val => val !== '' || ' 请选择通讯协议']">
                <template v-slot:no-option>
                  <div class="no-option" />
                </template>
                <template v-slot:before>
                  <label class="text-right name label-width">
                    <span class="text-red">*</span><span>通讯协议:</span>
                  </label>
                </template>
              </q-select>
              <q-select v-model="item.form.communicationTypeIot"
                        :options="item.methodsOption"
                        dense
                        options-dense
                        emit-value
                        map-options
                        outlined
                        class="select-width"
                        :rules="[ val => val !== '' || ' 请选择通讯方式']">
                <template v-slot:no-option>
                  <div class="no-option" />
                </template>
                <template v-slot:before>
                  <label class="text-right name label-width">
                    <span class="text-red">*</span><span>通讯方式:</span>
                  </label>
                </template>
              </q-select>
            </div>
          </div>
        </div>
      </div>
    </div>
    <q-separator />
    <div class="dialog-footer text-center margin-t-10">
      <q-btn outline label="上一步" color="primary" @click="preStep" class="q-mr-md"/>
      <q-btn unelevated label="下一步" color="primary" type="submit" :disable="!controllerType" :loading="submitting"/>
      <span style="color: #999999;cursor: pointer" class="margin-l-20" @click="skipBind">跳过</span>
    </div>
  </q-form>
</template>

<script>
import GatewayDetail from './gateway-detail'
import AddIcon from './add-icon'
import _ from 'lodash'
import { deviceBindBox, getDeviceCNC, getDeviceCascade, subDevices } from '../../../../../boot/miot/list'
import { Dialog } from 'quasar'

export default {
  name: 'config-gateway',
  components: {
    GatewayDetail,
    AddIcon
  },
  props: {
    boxId: {
      type: String,
      default: ''
    },
    productName: {
      type: String,
      default: ''
    },
    products: {
      type: Array,
      default: () => []
    },
    controllerType: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      submitting: false,
      tagValue: '1',
      typeOption: [],
      numOption: [],
      factoryOption: [],
      modelOption: [],
      protocolOption: [],
      methodsOption: [],
      tagTab: [],
      deviceMap: new Map(),
      subDevices: []
    }
  },
  computed: {
    tagTabTemp () {
      return _.cloneDeep(this.tagTab)
    },
    currentIndex () {
      return this.tagTab.findIndex(item => item.name === this.tagValue)
    }
  },
  watch: {
    productName: {
      immediate: true,
      handler: function (val) {
        if (val) {
          this.getDeviceCascade().then(() => {
            this.getSubDevices(this.boxId)
          })
        }
      }
    },
    tagTabTemp: {
      deep: true,
      handler: function (val, oldVal) {
        if (val) {
          val.forEach((_, index) => {
            if (val.name === oldVal.name && oldVal[index] && oldVal[index].form && val[index].numOption && val[index].numOption.length > 0) {
              // 设备类型改变
              if (val[index].form.deviceTypeIot !== oldVal[index].form.deviceTypeIot) {
                this.tagTab[index].modelOption = []
                this.tagTab[index].protocolOption = []
                this.tagTab[index].methodsOption = []
                this.tagTab[index].factoryOption = []
                this.tagTab[index].form.deviceFactoryIot = ''
                this.tagTab[index].form.deviceSerialIot = ''
                this.tagTab[index].form.deviceProtocolIot = ''
                this.tagTab[index].form.communicationTypeIot = ''
                const typeParentId = 0
                const data = this.deviceMap.get(val[index].form.deviceTypeIot + typeParentId)
                this.dataToOptions(data, this.tagTab[index].factoryOption)
              }

              // 设备厂家改变
              if (val[index].form.deviceFactoryIot !== oldVal[index].form.deviceFactoryIot) {
                this.tagTab[index].protocolOption = []
                this.tagTab[index].methodsOption = []
                this.tagTab[index].modelOption = []
                this.tagTab[index].form.deviceSerialIot = ''
                this.tagTab[index].form.deviceProtocolIot = ''
                this.tagTab[index].form.communicationTypeIot = ''
                const factoryParentId = this.tagTab[index].factoryOption.find(item => item.value === val[index].form.deviceFactoryIot) ? this.tagTab[index].factoryOption.find(item => item.value === val[index].form.deviceFactoryIot).parentId : ''
                const data = this.deviceMap.get(val[index].form.deviceFactoryIot + factoryParentId)
                this.dataToOptions(data, this.tagTab[index].modelOption)
              }

              // 设备型号改变
              if (val[index].form.deviceSerialIot !== oldVal[index].form.deviceSerialIot) {
                this.tagTab[index].protocolOption = []
                this.tagTab[index].methodsOption = []
                this.tagTab[index].form.deviceProtocolIot = ''
                this.tagTab[index].form.communicationTypeIot = ''
                const serialParentId = this.tagTab[index].modelOption.find(item => item.value === val[index].form.deviceSerialIot) ? this.tagTab[index].modelOption.find(item => item.value === val[index].form.deviceSerialIot).parentId : ''
                const data = this.deviceMap.get(val[index].form.deviceSerialIot + serialParentId)
                this.dataToOptions(data, this.tagTab[index].protocolOption)
              }

              // 通讯方式协议
              if (val[index].form.deviceProtocolIot !== oldVal[index].form.deviceProtocolIot) {
                this.tagTab[index].methodsOption = []
                this.tagTab[index].form.communicationTypeIot = ''
                const protocolParentId = this.tagTab[index].protocolOption.find(item => item.value === val[index].form.deviceProtocolIot) ? this.tagTab[index].protocolOption.find(item => item.value === val[index].form.deviceProtocolIot).parentId : ''
                const data = this.deviceMap.get(val[index].form.deviceProtocolIot + protocolParentId)
                this.dataToOptionsProtocolIot(data, this.tagTab[index].methodsOption)
              }
            } else {
              const typeParentId = 0
              this.dataToOptions(this.deviceMap.get(val[index].form.deviceTypeIot + typeParentId), this.tagTab[index].factoryOption)
              const factoryParentId = this.tagTab[index].factoryOption.find(item => item.value === val[index].form.deviceFactoryIot) ? this.tagTab[index].factoryOption.find(item => item.value === val[index].form.deviceFactoryIot).parentId : ''
              this.dataToOptions(this.deviceMap.get(val[index].form.deviceFactoryIot + factoryParentId), this.tagTab[index].modelOption)
              const serialParentId = this.tagTab[index].modelOption.find(item => item.value === val[index].form.deviceSerialIot) ? this.tagTab[index].modelOption.find(item => item.value === val[index].form.deviceSerialIot).parentId : ''
              this.dataToOptions(this.deviceMap.get(val[index].form.deviceSerialIot + serialParentId), this.tagTab[index].protocolOption)
              const protocolParentId = this.tagTab[index].protocolOption.find(item => item.value === val[index].form.deviceProtocolIot) ? this.tagTab[index].protocolOption.find(item => item.value === val[index].form.deviceProtocolIot).parentId : ''
              this.dataToOptionsProtocolIot(this.deviceMap.get(val[index].form.deviceProtocolIot + protocolParentId), this.tagTab[index].methodsOption)
            }
          })
        }
      }
    },
    subDevices: {
      immediate: true,
      handler: function (val) {
        if (val && val.length > 0) {
          const result = []
          val.map(item => {
            result.push({
              name: item.assetNumber,
              form: {
                assetNumber: item.assetNumber,
                deviceTypeIot: item.deviceTypeIot,
                deviceFactoryIot: item.deviceFactoryIot,
                deviceSerialIot: item.deviceSerialIot,
                deviceProtocolIot: item.deviceProtocolIot,
                communicationTypeIot: item.communicationTypeIot === 'LAN' || item.communicationTypeIot === 'lan' ? item.communicationTypeIot + '/PCMCIA' : item.communicationTypeIot
              },
              numOption: [{ 'label': item.assetNumber, 'value': item.assetNumber }],
              ispreStep: true,
              factoryOption: [],
              modelOption: [],
              protocolOption: [],
              methodsOption: []
            })
          })
          this.tagTab = result
          if (this.tagTab.length > 0) {
            this.tagValue = this.tagTab[0].name
          }
        }
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    // 关闭绑定子设备
    closeBind () {
      this.tagTab = []
    },
    // 跳过绑定
    skipBind () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要跳过此步骤吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        this.$emit('bindNone')
      })
    },
    init () {
      this.getDevice()
    },

    /**
     * 获取盒子下的子设备
     */
    async getSubDevices (val) {
      this.$q.loading.show()
      try {
        const { data } = await subDevices(val)
        if (data && data.length > 0) {
          this.subDevices = data
        } else {
          this.subDevices = []
        }
      } catch (e) {
      } finally {
        this.$q.loading.hide()
      }
    },

    async getDevice () {
      const { data } = await getDeviceCNC()
      this.numOption = data.map(item => {
        return {
          name: item.device_name,
          label: item.device_num,
          value: item.device_num
        }
      })
    },

    async getDeviceCascade () {
      const { data } = await getDeviceCascade(this.productName)
      if (data && data.children) {
        this.deviceToMap(data.children)
        this.dataToOptions(data.children, this.typeOption)
      }
    },

    deviceToMap (data) {
      if (data && data.length > 0) {
        data.forEach(item => {
          this.deviceMap.set(item.name + item.parentId, item.children)
          if (item.children && item.children.length > 0) {
            this.deviceToMap(item.children)
          }
        })
      }
    },

    dataToOptions (data, option) {
      if (data && data.length > 0) {
        data.forEach(item => {
          option.push({
            label: item.name,
            value: item.name,
            parentId: item.parentId
          })
        })
      }
    },
    dataToOptionsProtocolIot (data, option) {
      if (data && data.length > 0) {
        data.forEach(item => {
          option.push({
            label: item.name === 'LAN' || item.name === 'lan' ? item.name + '/PCMCIA' : item.name,
            value: item.name,
            parentId: item.parentId
          })
        })
      }
    },
    preStep () {
      this.$emit('preStep')
    },

    async submit () {
      // 如果不绑定任何子设备
      if (this.tagTab.length === 0) {
        const data = []
        data.push({
          boxNum: this.boxId
        })
        await deviceBindBox(data)
        this.$emit('bindNone')
        return
      }
      const data = []
      let productIdTotal = 0
      this.submitting = true
      this.tagTab.forEach(item => {
        // const productName = `${item.form.deviceTypeIot}_${item.form.deviceFactoryIot}_${item.form.deviceSerialIot}_${item.form.deviceProtocolIot}_${item.form.communicationTypeIot}`
        const index = this.products.findIndex(item => item.name === 'CNC_Model')
        if (index > -1) productIdTotal++
        data.push({
          ...item.form,
          productName: this.productName,
          productId: index > -1 ? this.products[index].product_id : '',
          boxNum: this.boxId
        })
      })
      // 如果没有匹配到id
      if (productIdTotal !== this.tagTab.length) {
        Dialog.create({
          title: `<p class="dialog-notice-title">
        <i class="iconfont icontubiao-52" ></i> 提示</p>`,
          message: `机床物模型不存在 无法创建`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          }
        })
        this.submitting = false
        return
      }
      try {
        // eslint-disable-next-line no-return-assign
        data.forEach(item => {
          item.communicationTypeIot = item.communicationTypeIot.indexOf('PCMCIA') > -1 ? item.communicationTypeIot.substring(0, 3) : item.communicationTypeIot
        })
        const rs = await deviceBindBox(data)
        if (rs.success) {
          this.$emit('successSubmit')
        } else {
          if (rs && rs.message) {
            this.$message.warning(rs.message)
          }
        }
      } catch (e) {
      } finally {
        this.submitting = false
      }
    },

    /**
     * 过滤获得assetNumOption
     */
    assetNumberOption () {
      return this.numOption.filter((item) => {
        return !this.tagTab.find(tag => tag.form.assetNumber === item.value)
      })
    },

    addTab () {
      this.tagTab.push({
        name,
        form: {
          assetNumber: '',
          deviceTypeIot: 'CNC',
          deviceFactoryIot: '',
          deviceSerialIot: '',
          deviceProtocolIot: '',
          communicationTypeIot: ''
        },
        numOption: this.assetNumberOption(),
        ispreStep: false,
        factoryOption: [],
        modelOption: [],
        protocolOption: [],
        methodsOption: []
      })
      this.tagValue = name
    },

    closeTab () {
      this.tagTab.splice(this.currentIndex, 1)
    }
  }
}
</script>

<style scoped lang="stylus">
.content-container
  display flex
  height 258px
  flex-direction column
  align-items center
  justify-content center
  .select-width
    width 266px
</style>
